package com.andengine.editor.factories;

import com.andengine.editor.atlaseditor.Atlas;
import com.andengine.editor.textureregioneditor.AtlasShort;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.ByteBufferInput;
import com.esotericsoftware.kryo.io.ByteBufferOutput;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.swingson.exceptions.ErrorMessageException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author sad
 */
public class AtlasFactory {

    private static final String atlasDir = "d:\\temp\\andengineTry\\atlasses\\";
    private static final AtlasFactory instance = new AtlasFactory();
    private static final String atlasFileExtension = ".atlas";

    public static AtlasFactory get() {
        return instance;
    }

    private AtlasFactory() {
    }

    public void save(String atlasName, Atlas atlas) {
        if (atlas.getAtlasId() == -1) {
            atlas.setAtlasId(UUID.randomUUID().getLeastSignificantBits());
        }
        Kryo kryo = new Kryo();
        try (Output output = new ByteBufferOutput(new GZIPOutputStream(new FileOutputStream(new File(atlasDir, atlasName + atlasFileExtension))))) {
            kryo.writeObject(output, atlas);
        } catch (IOException ex) {
            throw new ErrorMessageException(ex.getMessage());
        }
    }

    public Atlas read(String atlasName) {
        Kryo kryo = new Kryo();
        try (Input input = new ByteBufferInput(new GZIPInputStream(new FileInputStream(new File(atlasDir, atlasName + atlasFileExtension))))) {
            Atlas atlas = kryo.readObject(input, Atlas.class);
            return atlas;
        } catch (IOException ex) {
            throw new ErrorMessageException(ex.getMessage());
        }

    }

    public List<AtlasShort> getAtlasesNames() {
        File dir = new File(atlasDir);dir.exists();
        if(!dir.exists()){
            return new ArrayList<>();
        }
        List<AtlasShort> files = new ArrayList<>();
        for (File file : dir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(atlasFileExtension);
            }
        })) {
            String filePath = file.getAbsolutePath();
            String atlasName = filePath.substring(atlasDir.length());
            atlasName = atlasName.substring(0, atlasName.length() - atlasFileExtension.length());
            Atlas a = read(atlasName);
            files.add(new AtlasShort(a.getAtlasId(), atlasName));
        }

        return files;
    }
}
